package com.vecspace.datacenter.datatransform.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

import com.vecspace.database.model.ConnectionParam;
import com.vecspace.httpclient.THttpClient;
import com.vecspace.utils.log.HLogger;

/**
 * 
 * @author: wanghua
 */
public abstract class Http2DatabaseETL extends DataETL{

	@Override
	public boolean execute(String args) {
		Connection conn = null;		
		try{
			conn = this.getConnection();
			return doDataETL(conn, args);
		}catch(Exception ex){
			HLogger.DEFAULT().error(ex);
			return false;
		}
		finally{
			try {
				if(conn != null){
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**执行数据ETL作业
	 * 建议使用DbUtils工具类进行数据库操作。
	 * @param conn
	 * @param args
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	public abstract boolean doDataETL(Connection conn, String args) throws Exception;
	/**从http url上请求数据
	 * @param params
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected String requestData(Map<String, String> params) throws Exception{
		THttpClient httpclient = new THttpClient();
		String repstr = httpclient.get(url, charset);
		return repstr;
	}
	
	/**
	 * 
	 * 功能描述：
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected Connection getConnection() throws Exception{
		ConnectionParam connparam = connParam;
		Class.forName(connparam.getDriverClassName());
		Connection conn = DriverManager.getConnection(connparam.getUrl(),connparam.getUserId(),connparam.getPassword());
		return conn;
	}
	
	/**
	 * @param connparam
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected Connection getConnection(ConnectionParam connparam) throws Exception{
		if(connparam == null)return null;
		Class.forName(connparam.getDriverClassName());
		Connection conn = DriverManager.getConnection(connparam.getUrl(),connparam.getUserId(),connparam.getPassword());
		return conn;
	}
	
	private ConnectionParam connParam;
	private String url;
	private String mimeType = "text/json";
	private String charset = "utf-8";
	private String requestMethod = "POST";
	public ConnectionParam getConnParam() {
		return connParam;
	}

	public void setConnParam(ConnectionParam connParam) {
		this.connParam = connParam;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public String getMimeType() {
		return mimeType;
	}

	public void setMimeType(String mimeType) {
		this.mimeType = mimeType;
	}

	public String getRequestMethod() {
		return requestMethod;
	}

	public void setRequestMethod(String requestMethod) {
		this.requestMethod = requestMethod;
	}
	
}
